import axios from 'axios'
import { getToken, removeToken } from '@/utils/auth'
import store from '@/store'
import Vue from "vue";
import { Toast } from 'vant';
Vue.use(Toast);

// create an axios instance
const service = axios.create({
  baseURL: process.env.BASE_API, // api的base_url
  timeout: 1000 * 60, // request timeout
  transformRequest: [function (data) {
    let ret = ''
    for (let it in data) {
      ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
    }
    return ret
  }],
  headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})

// request interceptor
service.interceptors.request.use(config => {
  if (getToken()) {
    config.headers.Authorization = getToken()
    config.headers['reception_cookie_token'] = getToken()
  }

  return config
}, error => {
  // Do something with request error
  // console.log(error) // for debug
  Promise.reject(error)
})

// respone interceptor
service.interceptors.response.use(
  response => {
    const res = response.data
    if (res.status === 500) {
      // Toast.fail('失败文案');
      return Promise.reject('error')
    }
    if (res.status === 501) {
    //   MessageBox.alert('系统未登录，请重新登录', '未登录', {
    //     confirmButtonText: '确定',
    //     type: 'error'
    //   }).then(() => {
    //     store.dispatch('FedLogOut').then(() => {
    //       location.reload()
    //     })
    //   })
      return Promise.reject('error')
    } else if (res.status === 502) {
    //   MessageBox.alert('系统内部错误，请联系管理员维护', '错误', {
    //     confirmButtonText: '确定',
    //     type: 'error'
    //   })
      return Promise.reject('error')
    } else if (res.status === 503) {
    //   MessageBox.alert('请求业务目前未支持', '警告', {
    //     confirmButtonText: '确定',
    //     type: 'error'
    //   })
      return Promise.reject('error')
    } else if(res.status == 101 && res.msg == 102){ //登陆失效
      // store.dispatch('FedLogOut').then(() => {
        window.localStorage.clear()
        removeToken();
        this.$router.replace('/Login')
        location.reload()// In order to re-instantiate the vue-router object to avoid bugs
      // })

      return Promise.reject(res)
    }else if (res.status !== 100) {
      // 非5xx的错误属于业务错误，留给具体页面处理
      return Promise.reject(response)
    } else {
      // setTimeout(() => {
        // Toast.clear()
      // }, 500);
      return response
    }
  }, error => {
    // console.log('err' + error)// for debug
    // Message({
    //   message: '登录连接超时（后台不能连接，请联系系统管理员）',
    //   type: 'error',
    //   duration: 5 * 1000
    // })
    return Promise.reject(error)
  })

export default service
